package com.wzw.springboot.principle.mvc.model;

import com.wzw.springboot.principle.mvc.handler.ServletHandler;
import lombok.Data;
import org.springframework.http.HttpStatus;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 统一响应结果
 *
 * @author Wangzhiwen
 */
@Data
public class Result implements Serializable {

    private Integer code;

    private String message;

    public static Result ofSuccess() {
        return Result.ofSuccess(null);
    }

    public static Result ofSuccess(Object data) {
        return Result.ofSuccess(data, HttpStatus.OK.getReasonPhrase());
    }

    public static Result ofSuccess(Object data, String message) {
        int code = HttpStatus.OK.value();
        return ofSuccess(data, message, code);
    }

    public static Result ofSuccess(Object data, String message, Integer code) {
        SuccessResult result = new SuccessResult();
        result.setCode(code == null ? HttpStatus.OK.value() : code);
        result.setMessage(message);
        result.setData(data);
        return result;
    }

    public static Result ofFail(int code, String message, Exception e) {
        FailureResult result = new FailureResult();
        result.setCode(code);
        result.setMessage(message);
        result.setError(e.getLocalizedMessage());
        result.setPath(ServletHandler.getServletRequest().getRequestURI());
        result.setException(e.getClass().getName());
        result.setTimestamp(LocalDateTime.now());
        return result;
    }

}
